#------------------------------------------------#
# Script to convert MAC addresses to hostnames
# to store in a user file for use by wrtbwmon
# Usage:
# perl dns2user.pl <DNS_LEASE_FILE> <USER_FILE>
# DNS_LEASE_FILE is similar to dnsmasq.leases found
# in /tmp
#------------------------------------------------#

#!/usr/bin/perl
use strict;
use warnings;
use constant MAX_ARGS	=> 2;

my $ROUTER_DNS_FILE = undef;	# Original DNS file from router
my $USER_FILE = undef;		# Generated file to store user mappings
my $numArgs = undef;
my $mac_address = undef;
my $host_name = undef;
my @dns_data = undef;

my $result = 0;

$numArgs = @ARGV;

if ($numArgs <= 0 || $numArgs > MAX_ARGS) # Check if valid args
{
	$result = 0;	
	die "Invalid arguments (numArgs = ${numArgs}). See --help for info.\n";
}

# Continue with execution
$ROUTER_DNS_FILE = $ARGV[0];
if ($numArgs >= 2) # Second argument is user file name
{
	$USER_FILE = $ARGV[1];
} else {
	$USER_FILE = "dns_user.txt";
}

print "USER_FILE = ${USER_FILE}\n";

print "Router DNS File = ${ROUTER_DNS_FILE}\n";
open DNS_FILE, "<", $ROUTER_DNS_FILE or die $!;
open USER_FILE, ">", $USER_FILE or die $!;

print "File contents:\n";
while (my $line = <DNS_FILE>)
{
	$mac_address = "";
	$host_name = "";

	print "${line}";
	
	# Format of file dnsmasq.leases is:
	# DDDDD XX:XX:XX:XX:XX:XX DDD.DDD.D.DDD <string> XX:XX:XX:XX:XX:XX:XX
	# ([LEASE_TIME] [MAC_ADDRESS] [LAN_IP_ADDRESS] [HOST_NAME] [?])
	# Typically LEASE_TIME = 86400 = 1 day in seconds
	# Space delimited (D = decimal, X = hex) (No trailing newline)
	
	my @dns_data = split(' ', $line);
	
	foreach my $val (@dns_data) 
	{
#		print "$val\n";
	}
	
	$mac_address = @dns_data[1];
	$host_name = @dns_data[3];

#	print "mac_address = ${mac_address}, host_name = ${host_name}\n"; 

	# Write to USER_FILE format to be consumed by bwmon script:
	# mac_address,hostname
	# (one entry per line)
	print USER_FILE "${mac_address},${host_name}\n";
}

close USER_FILE;
close DNS_FILE;


